<template>
  <div>
    <!--title-->
    <div class="content-title" ref="title">
      <div class="su-title">
        <i class="el-icon-tickets"></i>
        <span>角色管理</span>
      </div>
      <div>
        <el-button type="primary" icon="el-icon-plus el-icon--left" @click="titleAddClick"> 添加角色</el-button>
      </div>
    </div>

    <!--tabs-->
    <div class="common-tabs" ref="tabs">
      <el-tabs v-model="tabsProp.active" @tab-click="tabsSwitchClick">
        <el-tab-pane name="1" label="已启动"/>
        <el-tab-pane name="2" label="未启动"/>
      </el-tabs>
    </div>

    <!--table配置-->
    <template>
      <!--表格前的按钮-->
      <div class="common-table-title-but" ref="tableTopBut"></div>
      <el-table
          ref="table"
          :data="tableData"
          border
          style="width: 100%"
          :max-height="tableProp.tableHeight"
          :header-cell-style="{background:'#f5f7fa',color:'#081333',fontWeight: 'normal'}"
          v-loading="tableProp.loading"
      >
        <el-table-column label="角色名称" min-width="150" :show-overflow-tooltip="true" align="center" prop="rolename"/>
        <el-table-column label="角色状态" min-width="150" :show-overflow-tooltip="true" align="center" prop="rolestatus"/>
        <el-table-column label="更新时间" min-width="150" :show-overflow-tooltip="true" align="center" prop="updateTime"/>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-view el-icon--left" @click="tableSeeClick(scope.row,0)">查看</el-button>
            <el-button type="danger" icon="el-icon-delete el-icon--left" @click="tableDelClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="common-pagination">
        <el-pagination
            @size-change="pageSizeChange"
            @current-change="pageCurrentChange"
            :current-page="paginationProp.currentPage"
            :page-sizes="[10, 20, 50, 100,500,1000]"
            :page-size="paginationProp.pageSize"
            layout="total,sizes, prev, pager, next, jumper"
            :total="paginationProp.total"
        />
      </div>
    </template>

    <!--抽屉-->
    <el-drawer
        :title="drawerProp.title"
        :visible.sync="drawerProp.isDrawer"
        direction="rtl"
        :append-to-body="true"
        :modal-append-to-body="false"
        custom-class="common-drawer"
        size="1050px"
    >
      <div class="common-drawer-content" v-loading="drawerProp.loading">
        <div class="parent">
          <!--左边-->
          <div class="leftChild">
            <ul class="content">
              <template v-for="(item,key) in drawerProp.leftProp">
                <li :key="key" :class="[drawerProp.active===key?'active':'']" @click="drawerActiveClick(key)">
                  {{ item }}
                </li>
              </template>
            </ul>
          </div>
          <!--右边-->
          <div class="rightChild">
            <ul class="content" ref="scrollViewRight" @wheel.passive="addWheelChange" :style="{'height': drawerProp.rightProp.height+'px'}">
              <li class="content-main" ref="drawerLi0">
                <!--标题-->
                <div class="title">
                  <span></span>
                  <label>基础设置</label>
                  <div class="s"></div>
                  <template v-if="drawerProp.status==='see'">
                    <div class="n" @click="drawerEdit">
                      <i class="el-icon-edit"></i>
                      编辑
                    </div>
                  </template>
                </div>
                <!--查看-->
                <div class="see" v-if="drawerProp.status==='see'">
                  <ul class="common-drawer-see">
                    <li class="common-drawer-see-li li2">
                      <span class="common-drawer-see-li-title">角色名称</span>
                      {{ formData.rolename }}
                    </li>
                    <li class="common-drawer-see-li">
                      <span class="common-drawer-see-li-title">角色状态</span>
                      <template v-for="item in rolestatusOption">
                        <template v-if="formData.rolestatus===item.value">
                          {{ item.label }}
                        </template>
                      </template>
                    </li>
                  </ul>
                </div>
                <!--修改-->
                <div class="edit" v-if="drawerProp.status==='edit' || drawerProp.status==='add'">
                  <el-form :model="formData" ref="drawerFrom0" class="common-drawer-edit">
                    <!--'li2':'','common-drawer-edit-li' li2一行-->
                    <el-form-item label="角色名称" prop="rolename" class="common-drawer-edit-li" :rules="[{required: true, message: '请输入角色名称', trigger: 'blur'}]">
                      <el-input placeholder="请输入角色名称" v-model="formData.rolename" clearable/>
                    </el-form-item>
                    <el-form-item label="状态" :prop="formData.rolestatus" class="common-drawer-edit-li li2">
                      <el-radio-group v-model="formData.rolestatus">
                        <el-radio v-for="(item,key) in rolestatusOption" :key="key" :label="item.value">
                          {{ item.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-form>
                </div>
              </li>
              <li class="content-main" ref="drawerLi1">
                <!--标题-->
                <div class="title">
                  <span></span>
                  <label>权限设置</label>
                  <div class="s"></div>
                  <template v-if="drawerProp.status==='see'">
                    <div class="n" @click="drawerEdit">
                      <i class="el-icon-edit"></i>
                      编辑
                    </div>
                  </template>
                </div>
                <!--查看-->
                <div class="see" v-if="drawerProp.status==='see'">
                  <el-tree
                      :data="treeData"
                      show-checkbox
                      node-key="smId"
                      ref="tree2"
                      default-expand-all
                      :default-checked-keys="formData.defaultTree"
                      :props="treeDefaultProps">
                  </el-tree>
                </div>
                <!--修改-->
                <div class="edit" v-if="drawerProp.status==='edit' || drawerProp.status==='add'">
                  <el-form :model="formData" ref="drawerFrom1" class="common-drawer-edit">
                    <!--'li2':'','common-drawer-edit-li' li2一行-->
                    <el-form-item class="li2">
                      <el-tree
                          :data="treeData"
                          show-checkbox
                          node-key="smId"
                          ref="tree"
                          default-expand-all
                          :default-checked-keys="formData.defaultTree"
                          :props="treeDefaultProps">
                      </el-tree>
                    </el-form-item>
                  </el-form>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div class="common-drawer-title-add-edit" v-if="drawerProp.status==='add'">
          <el-button
              icon="el-icon-close el-icon--left"
              @click="drawerProp.isDrawer=false"
          >
            取消
          </el-button>
          <el-button
              type="primary"
              icon="el-icon-check el-icon--left"
              @click="drawerSubmitForm('add')"
          >
            保存
          </el-button>
        </div>
        <div class="common-drawer-title-add-edit" v-if="drawerProp.status==='edit'">
          <el-button
              icon="el-icon-close el-icon--left"
              @click="drawerSubmitForm('see')"
          >
            取消
          </el-button>
          <el-button
              type="primary"
              icon="el-icon-check el-icon--left"
              @click="drawerSubmitForm('edit')"
          >
            保存
          </el-button>
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script>


export default {
  name: 'roleSetUp',
  components: {},
  props: [],
  data() {
    return {
      //接口名称
      apiProp: {
        tableInit: 'systemSettingsList',//表格初始化
        tableAdd: 'systemSettingsSave',//表格增加接口
        tableDel: 'systemSettingsDel',//表格删除接口
        tableEdit: 'systemSettingsSave',//表格修改接口
        tableQuery: 'systemSettingsQuery',//表格查一条接口
        drawerEdit: '',//抽屉改
        drawerQuery: '',//抽屉查
        selectApiBoolean: false,//下拉接口是否拉取过，解决页面进来只要拉取一次
      },
      //tabs 配置 1
      tabsProp: {
        active: "1",//tabs 默认选择哪个标题 空是0
        statusField: 'rolestatus',//切换的字段名
        SearchDropDown: true,//高级搜索下拉默认显示状态
      },

      //table 数据 1
      tableData: [],
      tableProp: {
        loading: false,
        tableHeight: 0,
      },

      //新增抽屉 配置
      drawerProp: {
        isDrawer: false,
        loading: false,
        title: '添加角色',
        active: 0,//左边选择了哪个
        status: 'add',// add 新增  see 查看
        leftProp: ['基本设置', '权限设置'],
        rightProp: {
          height: document.documentElement.clientHeight - 90,//右边高度
        }
      },
      //新增添加修改
      formData: {
        roleid: '',//id
        rolename: '',//名称
        roledesc: '',//我存的
        rolestatus: '1',//状态
        updateTime: '',//更新时间
        defaultTree: [],//树形 默认打开
      },
      treeData: [], //树数据
      //树形配置
      treeDefaultProps: {
        children: 'children',
        label: 'smCname',
      },
      //状态 选项
      rolestatusOption: [
        {label: '已启动', value: '1'},
        {label: '未启动', value: '2'},
      ],
      //分页配置 1
      paginationProp: {
        currentPage: 1,//当前第几页
        pageSize: 10,//每页几条
        total: 0,//总数
      },
    };
  },
  created() {
  },
  activated() {
    //权限树形值
    this.$systemSettingsSysMenus().then((result) => {
      this.treeData = result.datas;
    })
  },
  mounted() {
    this.initData();//数据初始化
    this.calculationHeight();//table计算高度

    //监听浏览器变化
    window.onresize = () => {
      return (() => {
        this.calculationHeight();//table计算高度
      })();
    };
  },
  watch: {
    //主要作用监听赋值给table高度
    'tabsProp.SearchDropDown'() {
      this.calculationHeight();//table计算高度
    },
  },
  methods: {
    //初始化数据 1
    initData() {
      this.tableProp.loading = true;
      //下拉接口
      let variableArray = [];//变量数组
      if (!this.apiProp.selectApiBoolean) {
        // const form1=new Promise((resolve)=>{
        // this.$().then((result) => {
        //   console.log(result);
        // resolve()
        // })
        // variableArray.push(form1)
        this.apiProp.selectApiBoolean = true;
      }
      Promise.all(variableArray).then(() => {
        if (this.apiProp.tableInit) {
          let params = {
            page: this.paginationProp.currentPage,
            row: this.paginationProp.pageSize,
          }
          params[`${this.tabsProp.statusField}`] = this.tabsProp.active
          this[`$${this.apiProp.tableInit}`](params).then((result) => {
            if (result.data) {
              if (result.data.length == 0) {
                if (this.paginationProp.currentPage != 1) {
                  this.paginationProp.currentPage = this.paginationProp.currentPage - 1;
                  this.initData()
                  return false;
                }
              }
              //去除管理员
              if (this.tabsProp.active == 1) {
                result.data.shift();
              }
              this.tableData = result.data.map(item => ({
                roleid: item.roleid,
                rolename: item.rolename,
                rolestatus: this.Utils.filterArray(item.rolestatus, this.rolestatusOption),
                updateTime: item.updateTime
              }));
              this.paginationProp.total = result.count;//总数
              this.tableProp.loading = false;
            } else {
              this.tableData = [];
              this.paginationProp.total = result.count;//总数
              this.tableProp.loading = false;
            }
          }, () => {
            this.tableProp.loading = false;
          })
        } else {
          this.tableProp.loading = false;
        }
      })
    },
    //title 我是新增按钮点击 1
    titleAddClick() {
      this.formData = this.$options.data().formData;
      this.$nextTick(function () {
        //Dom更新完毕
        this.$refs.tree.setCheckedKeys(this.formData.defaultTree);
      });
      this.drawerProp.isDrawer = true;
      this.drawerProp.loading = false;
      this.drawerProp.title = '添加角色';
      this.drawerProp.status = 'add';
      this.drawerActiveClick(0)
    },
    //tabs 切换点击 1
    tabsSwitchClick() {
      this.initData()
    },
    //抽屉左边 点击切换标题 1
    drawerActiveClick(key) {
      setTimeout(() => {
        let scrollHeight = 0;
        this.drawerLiArray = [];
        for (let i = 0; i < this.drawerProp.leftProp.length; i++) {
          this.drawerLiArray.push(this.$refs[`drawerLi${i}`].scrollHeight);
          if (key > i) {
            scrollHeight += this.$refs[`drawerLi${i}`].scrollHeight
          }
        }
        this.$refs.scrollViewRight.scrollTo(0, scrollHeight);
        this.drawerProp.active = key;
      }, 300)
    },
    //抽屉右边 监听鼠标滚动 1
    addWheelChange() {
      setTimeout(() => {
        let scrollTop = 0;
        for (let i = 0; i < this.drawerLiArray.length; i++) {
          scrollTop += this.drawerLiArray[i];
          if (scrollTop > this.$refs.scrollViewRight.scrollTop) {
            this.drawerProp.active = i;
            return false;
          }
        }
      }, 300)
    },
    //抽屉 点击编辑 1
    drawerEdit() {
      this.drawerProp.title = '编辑角色';
      this.drawerProp.status = 'edit'
    },
    //抽屉 点击保存 1
    drawerSubmitForm(status) {
      if (status === 'see') {
        this.drawerProp.status = 'see';
        this.tableSeeClick({roleid: this.formData.roleid});
        return false
      }

      let variableArray = [];//变量数组
      for (let i = 0; i < 1; i++) {
        variableArray.push(`form${i}`);
        variableArray[i] = new Promise((resolve) => {
          this.$refs[`drawerFrom${i}`].validate((valid) => {
            if (valid)
              resolve()
          })
        })
      }
      Promise.all(variableArray).then(() => {
        this.drawerProp.loading = true;
        let menu_ids = this.$refs.tree.getCheckedKeys(); //获取树数据
        let menu_id = this.$refs.tree.getHalfCheckedKeys();//半选数据
        let power_json = {all: menu_ids, one: menu_id};
        this.formData.roledesc = JSON.stringify(power_json);
        let data = JSON.parse(JSON.stringify(this.formData));
        delete data.roleProp
        this[`$${this.apiProp.tableAdd}`](data).then(() => {
          this.$message.success('保存成功');
          this.initData();
          if (status === 'add') {
            this.drawerProp.isDrawer = false;
            this.drawerProp.loading = false;
          } else {
            this.drawerProp.loading = false;
            this.drawerProp.status = 'see';
            this.tableSeeClick({roleid: this.formData.roleid})
          }
        }, () => {
          this.drawerProp.loading = false;
        })
      })


    },

    //table 计算高度 1
    calculationHeight() {
      setTimeout(() => {
        this.tableProp.tableHeight = document.documentElement.clientHeight - 215 - this.$refs.title.clientHeight - this.$refs.tabs.clientHeight - this.$refs.tableTopBut.clientHeight;
      }, 300)
    },
    //table 点击查看 1
    tableSeeClick(row, key) {
      this.formData = this.$options.data().formData;
      this.drawerProp.isDrawer = true;
      this.drawerProp.loading = true;
      this.drawerProp.title = '查看详细';
      this.drawerProp.status = 'see';
      if (key !== undefined) {
        this.drawerActiveClick(key)
      }
      let params = {
        roleid: row.roleid
      }
      this[`$${this.apiProp.tableQuery}`](params).then((result) => {
        this.formData.roleid = result.data.roleid;
        this.formData.rolename = result.data.rolename;
        this.formData.roledesc = result.data.roledesc;
        this.formData.rolestatus = result.data.rolestatus;
        this.formData.updateTime = this.Utils.stampData13(result.data.updateTime);
        //树形
        this.formData.defaultTree = JSON.parse(result.data.roledesc).all;
        this.$nextTick(function () {
          //Dom更新完毕
          this.$refs.tree2.setCheckedKeys(this.formData.defaultTree);
        });
        this.drawerProp.loading = false;
      })
    },
    //table 点击删除 1
    tableDelClick(row) {
      this.$confirm('此操作将永久删除, 是否继续?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          roleid: row.roleid
        }
        this[`$${this.apiProp.tableDel}`](data).then(() => {
          this.$message.success('删除成功');
          this.initData();
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    //分页 选择了每页几条 1
    pageSizeChange(val) {
      this.paginationProp.currentPage = 1;//当前第几页
      this.paginationProp.pageSize = val;//每页几条
      this.initData();
    },
    //分页 点击了跳转到第几页 1
    pageCurrentChange(val) {
      this.paginationProp.currentPage = val;//当前第几页
      this.initData();
    },

  },
};
</script>

<style lang="scss" scoped>
</style>
